package top.dotgo.web.admin.oauth.service.impl;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @author jornl
 * @date 2020/2/25 0:36 星期二
 */
public class SingleTokenServices extends DefaultTokenServices {

    private int accessTokenValiditySeconds = 60 * 60 * 12;
    private TokenStore tokenStore;

    @Override
    public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) {
        OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication);
        if (existingAccessToken != null) {
            if (existingAccessToken.getRefreshToken() != null) {
                OAuth2RefreshToken refreshToken = existingAccessToken.getRefreshToken();
                tokenStore.removeRefreshToken(refreshToken);
            }
            tokenStore.removeAccessToken(existingAccessToken);
        }
        super.setTokenStore(tokenStore);
        return super.createAccessToken(authentication);
    }

    @Override
    public void setRefreshTokenValiditySeconds(int refreshTokenValiditySeconds) {
        super.setRefreshTokenValiditySeconds(refreshTokenValiditySeconds);
    }

    @Override
    public void setAccessTokenValiditySeconds(int accessTokenValiditySeconds) {
        this.accessTokenValiditySeconds = accessTokenValiditySeconds;
        super.setAccessTokenValiditySeconds(accessTokenValiditySeconds);
    }

    @Override
    public void setSupportRefreshToken(boolean supportRefreshToken) {
        super.setSupportRefreshToken(supportRefreshToken);
    }

    @Override
    public void setReuseRefreshToken(boolean reuseRefreshToken) {
        super.setReuseRefreshToken(reuseRefreshToken);
    }

    @Override
    public void setTokenStore(TokenStore tokenStore) {
        this.tokenStore = tokenStore;
        super.setTokenStore(tokenStore);
    }

    @Override
    public void setClientDetailsService(ClientDetailsService clientDetailsService) {
        super.setClientDetailsService(clientDetailsService);
    }

    public void setAccessTokenEnhancer(TokenEnhancer accessTokenEnhancer) {
        super.setAccessTokenValiditySeconds(accessTokenValiditySeconds);
    }

    @Override
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }
}
